package com.starblink.library.widget.wishlist

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.postDelayed
import androidx.lifecycle.lifecycleScope
import com.apollographql.apollo3.api.Optional
import com.blankj.utilcode.util.VibrateUtils
import com.skydoves.balloon.balloon
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.CoroutineUpdateTask
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.ext.load
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.library.widget.balloon.MoreSettingBalloonFactory
import com.starblink.library.widget.databinding.ViewWishlistDetailsItemBinding
import com.starblink.library.widget.product.parity.PriceParityDialog
import com.starblink.library.widget.product.pop.WishListFindSimilarKetaiPop
import com.starblink.library.widget.product.pop.WishListFindSimilarPop
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.rocketreserver.CancelCollectionProductMutation
import com.starblink.rocketreserver.FetchProductListByStdIdIgnoreCountryQuery
import com.starblink.rocketreserver.MoveProductList2WishListMutation
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.CollectItem
import com.starblink.rocketreserver.type.StdProductIdQuery
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

/**
 * 心愿单收藏商品列表项视图
 */
class WishlistDetailItemView @JvmOverloads constructor(
    context: Context,
    attrSet: AttributeSet?,
    defStyleAttr: Int = 0,
) : FrameLayout(context, attrSet, defStyleAttr) {


    private val collectImg = R.mipmap.ic_prd_collect
    private val collectedImg = R.mipmap.ic_prd_collected
    private val strOn = CommUtils.getString(R.string.on)
    private val strWishPeople = CommUtils.getString(R.string.people_wish)
    private val viewing = CommUtils.getString(R.string.viewing)

    private val binding =
        ViewWishlistDetailsItemBinding.inflate(LayoutInflater.from(context), this, true)


    private var wishlistId: String? = null
    private var spmPageValue: Int = 0
    private var isFirstItem: Boolean = false
    private var position: Int = 0

    // 更多设置弹窗
    private val balloonMoreSetting by binding.root.balloon<MoreSettingBalloonFactory>()
    private val balloonWishGuide by binding.root.balloon<WishlistGuide01BalloonFactory>()


    private lateinit var productS: ProductF
    private var deleteClickCallbackS: ((
        result: Boolean,
    ) -> Unit)? = null
    private var moveClickCallbackS: ((
        result: Boolean,
    ) -> Unit)? = null

    private val findSimilarPop by lazyOnNone {
        WishListFindSimilarPop(context, addBoardClick = {
            if (wishlistId == null) {
                doAddToBoard(productS)
            } else {
                doAddToBoard(productS, wishlistId)
            }
        }, deleteClick = {
            doDeleteProduct(wishlistId, productS, deleteClickCallbackS)
        })
    }

    private val findSimilarKetaiPop by lazyOnNone {
        WishListFindSimilarKetaiPop(context, addBoardClick = {
            doAddToBoard(productS, wishlistId)
        })
    }

    init {
        val typedArray = context.obtainStyledAttributes(
            attrSet,
            R.styleable.PriceView
        )
        binding.laySidesLipDelete.setSwipeEnable(
            typedArray.getBoolean(
                R.styleable.PriceView_pvSwipeEnable,
                true
            )
        )
        typedArray.recycle()
    }

    /**
     * @param isSelf true-我的心愿单；false-他人心愿单
     * @param wishlistId null表示心愿单已收藏商品， 非null表示心愿单商品详情页
     */
    @SuppressLint("SetTextI18n")
    fun setData(
        showChoiceMode: Boolean = false,
        hasChoice: Boolean = false,
        isSelf: Boolean = false,
        wishlistId: String? = null,
        product: ProductF,
        spmPageValue: Int,
        position: Int,
        isFirstItem: Boolean = false,
        choiceClickCallback: ((
            result: Boolean,
        ) -> Unit),
        deleteClickCallback: ((
            result: Boolean,
        ) -> Unit)? = null,
        moveClickCallback: ((
            result: Boolean,
        ) -> Unit)? = null,
    ) {

        this.position = position
        this.wishlistId = wishlistId
        this.productS = product
        this.deleteClickCallbackS = deleteClickCallback
        this.moveClickCallbackS = moveClickCallback
        this.spmPageValue = spmPageValue
        this.isFirstItem = isFirstItem

        // 埋点：心愿单商品点击
        binding.boardDetailsLay.trackData(
            page = spmPageValue,
            element = SpmElementDef.GoodCollectionCard,
            params = spmMap(product),
//            businessSuffixID = businessSuffixId(
//                beanStr = "ProductF",
//                id = product.id
//            ),
            businessSuffixID = businessSuffixId(product),
            onlyHit = true
        )
        // 埋点：心愿单商品曝光
        trackData(
            page = spmPageValue,
            element = SpmElementDef.GoodCollectionCard,
            params = spmMap(product),
//            businessSuffixID = businessSuffixId(
//                beanStr = "ProductF",
//                id = product.id
//            )
            businessSuffixID = businessSuffixId(product)
        )

        //多选模式
        if (showChoiceMode) {
            binding.boardDetailsLay.height(142.dp)
//            binding.tvBrandRightLay.setPadding(12.dp, 16.dp, 8.dp, 14.dp)
            binding.lgChoice.visible()
            binding.tvMoreSetting.gone()
            handleStoreSet(product, true)
            binding.similarBtn.gone()
            binding.imgCollect.gone()

            if (hasChoice) {
                binding.lgChoice.setImageDrawable(CommUtils.getDrawable(R.drawable.ic_checkbox_true))
            } else {
                binding.lgChoice.setImageDrawable(CommUtils.getDrawable(R.drawable.ic_checkbox_false))
            }
            binding.lgChoice.setOnClickListener {
                choiceClickCallback.invoke(!hasChoice)
            }

        } else {
            binding.boardDetailsLay.height(206.dp)
//            binding.tvBrandRightLay.setPadding(12.dp, 16.dp, 8.dp, 70.dp)
            binding.lgChoice.gone()
            binding.tvMoreSetting.visible()
            handleStoreSet(product, false)
            binding.similarBtn.visible()
            binding.imgCollect.visible()
        }

        binding.boardDetailsLay.click {
            goH5Web(product, showChoiceMode)
        }

        //左侧
        binding.mainImg.enableCorner(12.dp2px())
        binding.mainImg.load(product.mainImg)
        binding.mainImg.click {
            goH5Web(product, showChoiceMode)
            trackData(
                page = spmPageValue,
                element = SpmElementDef.GoodCollectionCard,
                params = spmMap(product),
                businessSuffixID = businessSuffixId(product),
                onlyHit = true
            )
        }
        binding.mainImg.setOnLongClickListener {
            //if (true) return@setOnLongClickListener false
            if (binding.mainImg.drawable == null) return@setOnLongClickListener false
            if (product.valid == false) return@setOnLongClickListener false

            VibrateUtils.vibrate(100L)
            if (product?.mainImg.isNullOrEmpty() || product?.id.isNullOrEmpty() || product?.type == null) {
                return@setOnLongClickListener false
            }

            if (isSelf) {
                findSimilarPop.showPopup(
                    binding.mainImg,
                    product.mainImg!!,
                    product.id!!,
                    product.type
                )
            } else {
                findSimilarKetaiPop.showPopup(
                    binding.mainImg,
                    product.mainImg!!,
                    product.id!!,
                    product.type
                )
            }
            true
        }


//        binding.brandTxt.isSelected = true
        //是否有效
        if (product.valid == true) {
            //有效
            binding.mainImgInvalid.gone()
            //无效时将比价置为识图
//            binding.tvBrandLay.visible()
            binding.similarImg.gone()
            binding.similarTxt.text =
                CommUtils.getString(R.string.compare_price)
        } else {
            binding.mainImgInvalid.visible()
            //无效时将比价置为识图
//            binding.tvBrandLay.gone()
            binding.similarImg.visible()
            binding.similarTxt.text =
                CommUtils.getString(R.string.Find_Similar)
        }


        //右侧
        //右侧
        //右侧
        //右侧

        //标签
        binding.tvBrandTag.visibleOrGone(product.hotBrand?.name.isNullOrBlank().not()) {
            text = product.hotBrand?.name?.uppercase()
        }
        if (showChoiceMode) {
            if (product.hotBrand?.name.isNullOrBlank()) {
                binding.tvBrandLay.gone()
            } else {
                binding.tvBrandLay.visible()
            }
        } else {
            binding.tvBrandLay.visible()
        }

        var linesAdd = 0
        if (product.valid == true) {
            // on XX people\'s wishlists
            if ((product.voteNum ?: 0) > 0) {
                linesAdd++
                binding.tvVoteNum.visible()
                binding.tvVoteNum.text = "$strOn ${product.voteNum} $strWishPeople"
            } else {
                binding.tvVoteNum.gone()
            }

            //views
            if ((product.viewNum ?: 0) > 0) {
                linesAdd++
                binding.tvViewingNum.visible()
                binding.tvViewingNum.text = "${product.viewNum} $viewing"
            } else {
                binding.tvViewingNum.gone()
            }
            //价格
            if ((product.price ?: 0.0) > 0) {
//                if(product.price==9.0){
//                    YYLogUtils.e("9527 -- ${product.price} ${product.id} ${product.disCountInfo?.underlinePrice}")
//                }
                binding.tvPrice.visible()
                binding.tvPrice.show(
                    product.price!!,
                    product.currency,
                    product.currencySymbol
                )
                product.disCountInfo?.underlinePrice?.let {
                    binding.tvPrice.showStyleHasOff(
                        product.price!!,
                        product.currency,
                        product.currencySymbol
                    )
                    binding.tvPriceOff.visible()
                    binding.tvPriceOff.show(
                        it,
                        product.currency,
                        product.currencySymbol
                    )
                }
            } else {
                binding.tvPriceOff.visible()
                binding.tvPrice.gone()
            }
            //是否是低价商品
            binding.tvPriceLowest.visibleOrGone(product.minimumPriceFlag ?: false)
            //支付方式
            if (product.klarnaPayFlag == true || "Free Shipping".equals(
                    product.logistics?.shippingTag,
                    ignoreCase = true
                )
            ) {
                linesAdd++
                binding.payTypeFreeShipping.visible()
            } else {
                binding.payTypeFreeShipping.gone()
            }

            if (product.klarnaPayFlag == true) {
                binding.payType.visible()
            } else {
                binding.payType.gone()
            }
            //物流
            if ("Free Shipping".equals(product.logistics?.shippingTag, ignoreCase = true)) {
                binding.freeShipping.visible()
            } else {
                binding.freeShipping.gone()
            }
        } else {
            binding.tvVoteNum.gone()
            binding.tvViewingNum.gone()
            binding.tvPrice.gone()
            binding.tvPriceLowest.gone()
            binding.payTypeFreeShipping.gone()
            binding.payType.gone()
            binding.freeShipping.gone()
        }

        //更多
        binding.tvMoreSetting.click {
            showMoreSettingPopup(
                view = it,
                product,
                isSelf,
                wishlistId,
                deleteClickCallback,
                moveClickCallback
            )
        }
        if (isFirstItem) {
            handleWishlistGuide(binding.tvMoreSetting, position)
        }
        binding.tvMoreSetting.trackData(
            page = spmPageValue,
            element = SpmElementDef.Element_33043,
            onlyHit = true,
            params = spmMap(product)
        )

        //处理前台属性
        if (product.frontPropertyList.isNullOrEmpty()) {
            binding.tvFrontAttr.gone()
        } else {
            linesAdd++
            binding.tvFrontAttr.visible()
            var attrString = ""
            var tag1 = 0
            product.frontPropertyList?.forEach { property ->
                if (tag1 == product.frontPropertyList!!.size - 1) {
                    property.value?.let {
                        attrString += it
                    }
                } else {
                    property.value?.let {
                        attrString += "$it | "
                    }
                }
                tag1++
            }
            if (attrString.isEmpty()) {
                binding.tvFrontAttr.gone()
            } else {
                binding.tvFrontAttr.text = attrString
            }
        }


        if (linesAdd > 1) {
            binding.tvName.maxLines = 1
        } else {
            binding.tvName.maxLines = 2
        }

        //标题
        if (product.title.isNullOrBlank()) {
            binding.tvName.gone()
        } else {
            binding.tvName.visible()
            binding.tvName.text = product.title
        }


        // 收藏按钮，仅当查看他人心愿单时可见
        binding.btnAddToBoard.enableCorner(12.dp, "bottom")
        binding.imgCollect.visibleOrGone(!isSelf) {
            updateCollect(product.collected)
            click { doCollectProduct(product) }
        }

        handleLeftTopTag(product)
//        binding.newInListLay.gone()

        binding.similarBtn.click { doFindSimilar(product) }

        //侧滑删除
        binding.deleteBtn.click {
            doDeleteProduct(wishlistId, product, deleteClickCallback)
        }
    }

    var task: CoroutineUpdateTask? = null
    private fun handleWishlistGuide(view: View, pos: Int) {
//        if (task == null) {
//            task = CoroutineUpdateTask()
//        }
//        task?.scheduleUpdate(500, action = {
//            if (view.isInScreen() && SkStorage.getInt(UserDataCenter.HOME_TAB_INDEX, 0) == 2) {
//                view.post {
//                    balloonWishGuide.showAlignTop(view)
//                    SkNoviceManage.hasPopGuide(SkGuideEnum.WISHLIST_MORE_SETTING_1_13)
//                }
//                task?.cancel()
//            }
//        })
    }

    private fun goH5Web(product: ProductF, showChoiceMode: Boolean) {
        if (product.valid == true && !showChoiceMode) {
            product.id?.let { it1 ->
                product.merchantWeb?.let { it2 ->
                    CommonRoute.startProductLink(
                        activity = context,
                        webUrl = product.url,
                        id = it1,
                        productId = product.productId ?: "",
                        standardSpuIds = product.standardSpuIds ?: "",
                        collect = product.collected == true,
                        type = product.type,
                        storeId = it2.id,
                        storeName = it2.merchantName ?: "",
                        storeLogo = it2.logo,
                        storeFollow = it2.subOrNot,
                        affInfoLink = product.affInfo?.link,
                        traceId = product.traceId ?: ""
                    )
                }
            }
        }
    }

    /**
     * 收藏商品
     */
    private fun doCollectProduct(product: ProductF, fromPopupWindow: Boolean = false) {
        SkGqlClient.defaultLoadingShow(true)
        CommonMutateManage.collectProduct(
            ctx = context,
            id = product.id!!,
            type = product.type,
            collected = (product.collected == true),
            refreshState = {
                updateCollect(product.collected != true)
            }
        ) { it, collected ->
            SkGqlClient.defaultLoadingDismiss(true)
            if (it) {
                // 收藏或取消收藏成功，更新数据
                product.apolloValue("collected", collected)
                // 收藏成功，显示Add To Board提示
                binding.btnAddToBoard.visibleOrGone(product.collected == true) {
                    this.animation =
                        AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
                            .apply {
                                duration = 500L
                            }
                    this.animation?.start()
                    this.postDelayed(3000L) {
                        this.gone()
                    }
                    this.setOnClickListener {
                        WishlistAddBottomDialog.showAddListDialog(
                            context,
                            batchPros = arrayListOf(
                                BatchProductArrEntry(
                                    id = product.id ?: "",
                                    type = product.type,
                                    url = product.mainImg ?: ""
                                )
                            ),
                            spmPageValue = spmPageValue
                        )
                    }
                }
                // 埋点:客态item页/客态心愿单详情页-商品收藏/客态心愿单详情页-找相似-收藏
                var element: Int = if (fromPopupWindow) {
                    SpmElementDef.POP_FIND_SIMILAR_ADD
                } else {
                    SpmElementDef.itemCardCollection
                }
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            spmPageValue,
                            element
                        ),
                        params = spmMap(product, product.collected)
                    )
                )
            } else {
                // 收藏或取消收藏失败，恢复UI状态
                updateCollect(product.collected)
            }
        }
    }

    /**
     * 删除商品
     */
    private fun doDeleteProduct(
        wishlistId: String?,
        product: ProductF,
        deleteClickCallback: ((result: Boolean) -> Unit)?
    ) {
        ConfirmDialog.Builder(context)
            .setMessage(
                "Are you sure you want to\n" +
                        "delete this from your ${if (wishlistId == null) "Items" else "Board"}?"
            )
            .setCancelButton(com.starblink.basic.style.R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }
            .setSureButton(com.starblink.basic.style.R.string.delete) { dialog, _ ->
                dialog.dismiss()
                doCollectGoods(product) { result ->
                    if (result) {
                        product.apolloValue("subOrNot", false)
                        theScope.launch {
                            FlowBus.with<List<ProductF>>(FlowConst.WISHLIST_DELETE_PRODUCT_VIEW)
                                .post(listOf(product))
                        }
                        toastWishlist("Removed successfully")
                    }
                    deleteClickCallback?.invoke(result)
                }
            }
            .setCanCancel(true)
            .create().show()
    }

    /**
     * 查找相似
     */
    private fun doFindSimilar(product: ProductF) {
        //无效
        if (product.valid == false) {
            if (product.mainImg.isNullOrEmpty() || product.id.isNullOrEmpty()) {
            } else {
                CommonRoute.toFindSimilarGoods(product.mainImg!!, product.id!!, product.type)
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            spmPageValue,
                            SpmElementDef.Element_33044
                        ),
                        params = spmMap(product)
                    )
                )
            }
        } else {
            showParityDialog(product)
        }
    }

    private fun spmMap(product: ProductF, result: Boolean? = null): Map<String, String> {
        val res = mutableMapOf(
            "id" to (product.id ?: ""),
            "productId" to (product.productId ?: ""),
            "standardSpuIds" to (product.standardSpuIds ?: ""),
            "type" to product.type.toString(),
            "merchantName" to (product.merchantWeb?.merchantName ?: ""),
            "index" to "$position"
        )
        result?.let {
            res["result"] = if (result) "1" else "0"
            res["status"] = if (UserDataCenter.isLogin()) "1" else "0"
        }
        return res
    }

    private fun showMoreSettingPopup(
        view: View,
        product: ProductF,
        isSelf: Boolean,
        wishlistId: String?,
        deleteClickCallback: ((result: Boolean) -> Unit)?,
        moveClickCallback: ((result: Boolean) -> Unit)?,
    ) {
        YYLogUtils.e("  isSelf  -->$isSelf")

        val balloonView = balloonMoreSetting.getContentView()
        val vFindSimilar =
            balloonView.findViewById<View>(com.starblink.library.widget.R.id.find_similar)

        vFindSimilar.trackData(
            page = spmPageValue,
            element = SpmElementDef.Element_33044,
            onlyHit = true,
            params = spmMap(product)
        )

        vFindSimilar.click {
            // 找相似
            if (product.mainImg.isNullOrEmpty() || product.id.isNullOrEmpty()) {
                toast("data error")
            } else {
                CommonRoute.toFindSimilarGoods(product.mainImg!!, product.id!!, product.type)
            }

            balloonMoreSetting.dismiss()

        }
        if (isSelf) {
            // 我的心愿单
            val vDelete =
                balloonView.findViewById<View>(com.starblink.library.widget.R.id.delete_collected_product)
            vDelete.visible()
            vDelete.click {
                // 删除商品
                doDeleteProduct(wishlistId, product, deleteClickCallback)
                balloonMoreSetting.dismiss()
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            spmPageValue,
                            SpmElementDef.Element_31107
                        ),
                        params = spmMap(product)
                    )
                )
            }

            if (wishlistId == null) {
                // 我的心愿单-All Items页面
                val vAddToBoard =
                    balloonView.findViewById<View>(com.starblink.library.widget.R.id.add_to_board)
                vAddToBoard.visible()
                vAddToBoard.click {
                    doAddToBoard(product)
                    balloonMoreSetting.dismiss()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                spmPageValue,
                                SpmElementDef.POP_FIND_SIMILAR_ADD
                            ),
                            params = spmMap(product, result = true)
                        )
                    )
                }
            } else {
                // 我的心愿单-Wishlist Detail页面
                val vMoveToBoard =
                    balloonView.findViewById<View>(com.starblink.library.widget.R.id.move_to_board)
                vMoveToBoard.visible()
                vMoveToBoard.click {
                    // 移入心愿单中
                    doMoveToBoard(product, wishlistId, moveClickCallback)
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                spmPageValue,
                                SpmElementDef.POP_FIND_SIMILAR_ADD
                            ),
                            params = spmMap(product, result = true)
                        )
                    )
                    balloonMoreSetting.dismiss()
                }
            }
        } else {
            // 他人心愿单
            val vAddToBoard =
                balloonView.findViewById<View>(com.starblink.library.widget.R.id.add_to_board)
            vAddToBoard.visibleOrGone(product.collected == true) {
                vAddToBoard.click {
                    doAddToBoard(product)
                    balloonMoreSetting.dismiss()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                spmPageValue,
                                SpmElementDef.POP_FIND_SIMILAR_ADD
                            ),
                            params = spmMap(product, result = true)
                        )
                    )
                }
            }

            val vCollect =
                balloonView.findViewById<View>(com.starblink.library.widget.R.id.collect)
            vCollect.visible()
            vCollect.click {
                doCollectProduct(product, fromPopupWindow = true)
                balloonMoreSetting.dismiss()
            }
            val vCollectTitle =
                balloonView.findViewById<TextView>(com.starblink.library.widget.R.id.collect_title)
            vCollectTitle.text = if (product.collected == true) "Unadded" else "Add To"

            val vCollectImg =
                balloonView.findViewById<ImageView>(com.starblink.library.widget.R.id.collect_img)
            vCollectImg.setImageResource(if (product.collected == true) com.starblink.library.widget.R.drawable.ic_wishlist_product_collected else com.starblink.library.widget.R.drawable.ic_wishlist_product_collect)
        }

        balloonMoreSetting.showAlignBottom(view)
    }

    private fun doAddToBoard(
        product: ProductF,
        excludeWishlistId: String? = null
    ) {
        WishlistAddBottomDialog.showAddListDialog(
            context,
            batchPros = arrayListOf(
                BatchProductArrEntry(
                    id = product.id ?: "",
                    type = product.type,
                    url = product.mainImg ?: ""
                )
            ),
            spmPageValue = spmPageValue,
            excludeWishlistId = excludeWishlistId
        )
    }

    private fun doMoveToBoard(
        product: ProductF,
        excludeWishlistId: String? = null,
        deleteClickCallback: ((result: Boolean) -> Unit)? = null
    ) {
        WishlistAddBottomDialog.showAddListDialog(
            context,
            batchPros = arrayListOf(
                BatchProductArrEntry(
                    id = product.id ?: "",
                    type = product.type,
                    url = product.mainImg ?: ""
                )
            ),
            spmPageValue = spmPageValue,
            excludeWishlistId = excludeWishlistId
        )
    }

    /**
     * 收藏按钮
     */
    private fun updateCollect(collected: Boolean?) {
        binding.imgCollect.setImageResource(if (collected == true) collectedImg else collectImg)
    }


    private fun doCollectGoods(
        product: ProductF,
        collClickCallback: ((
            result: Boolean,
        ) -> Unit),
    ) {
        deleteItemsFromBoards(product) {
            collClickCallback.invoke(it)
        }
    }

    //# 批量移动商品从心愿单A到心愿单B。前提: 原本已收藏 [登录态]
//    # 0 到 a, 表示把商品从 allItems 加到 心愿单A
//    # a 到 b, 表示把商品从 心愿单A  移到 心愿单B
//    # a 到 0, 表示把商品从 心愿单A 移除
//    moveProductList2WishList(items:[CollectItem], "from心愿单Id" fromWishListId:Long!=0, "目标心愿单Id" toWishListId:Long!=0):Boolean!
    private fun deleteItemsFromBoards(
        product: ProductF,
        collClickCallback: ((
            result: Boolean,
        ) -> Unit),
    ) {


        if (wishlistId == null) {
            MainScope().launch {
                var result = SkGqlClient.skMutation(
                    CancelCollectionProductMutation(
                        id = product.id!!,
                        type = product.type
                    ),
                    showDefaultLoading = true
                )?.data?.cancelCollectionProduct
                result?.let {
                    if (result == true) {
                        collClickCallback.invoke(true)
                        FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
                    }
                }
            }
        } else {
            MainScope().launch {
                var result = SkGqlClient.skMutation(
                    MoveProductList2WishListMutation(
                        items = Optional.present(
                            listOf(
                                CollectItem(
                                    id = product.id!!,
                                    type = product.type.optional(),
                                    outOfferId = Optional.present(product.outOfferId)
                                )
                            )
                        ),
                        fromWishListId = Optional.present(wishlistId!!),
                        toWishListId = Optional.present(0),
                    ),
                    showDefaultLoading = true
                )?.data?.moveProductList2WishList

                result?.let {
                    if (result == true) {
                        collClickCallback.invoke(true)
                        FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
                    }
                }
            }
        }
    }


    /**
     * 左上角标签
     */
    private fun handleLeftTopTag(product: ProductF) {


        if (product?.disCountInfo?.discountText?.isNotEmpty() == true) {
            binding.tvLeftTag.gone()
            binding.tvDiscount.visible()
            binding.tvDiscount.text = product?.disCountInfo?.discountText
        } else {
            binding.tvDiscount.gone()
            if (!product.cornerLabels.isNullOrEmpty() && product.cornerLabels!!.isNotEmpty() && product.valid == true) {
                val type = product.cornerLabels!![0].type
                if (type == 1 || type == 2 || type == 3 || type == 4) {
                    binding.tvLeftTag.visible()
                    if (type == 3) {
                        binding.tvLeftTag.setBackgroundColor(CommUtils.getColor(R.color.sk_red600))
                    } else {
                        binding.tvLeftTag.setBackgroundColor(CommUtils.getColor(R.color.sk_gray600))
                    }
                    binding.tvLeftTagTxt.text = product.cornerLabels!![0].title
                } else {
                    binding.tvLeftTag.gone()
                }
            } else {
                binding.tvLeftTag.gone()
            }
        }
    }


    private fun handleStoreSet(product: ProductF, hide: Boolean) {

        if (hide) {
            binding.leftImgTxtLay.gone()
        } else {
            binding.leftImgTxtLay.visible()
        }

        binding.leftImgTxtLay.click {
            if (product.valid == true) {
                if (product.type == 1) {
                    product.merchantWeb?.id?.let { id ->
                        CommonRoute.startStoreDetail(context, id)
                    }
                } else if (product.type == 2) {
                    showParityDialog(product)
                }
            }
        }



        YYLogUtils.e("valid ---->${product.valid}")
        if (product.valid == true) {


            val type = product.type
            val prdNum = product.productNum ?: 0
            var subOrNot = false
            var shopName = ""
            var url = ""
            val productList = product.offerList
            if (type == 1) {
                val v0 = product.merchantWeb
                v0?.let {
                    url = v0.logo ?: ""
                    shopName = v0.merchantName ?: ""
                    subOrNot = v0.subOrNot
                }
            } else if (type == 2) {
                val itemLogos = product.offerList
                val logos = arrayListOf<String>()
                itemLogos?.let {
                    it.forEach { elm ->
                        if (!(elm?.spuOffer?.merchantWeb?.logo.isNullOrBlank())) {
                            logos.add(elm!!.spuOffer.merchantWeb!!.logo!!)
                        }
                    }
                }
                if (logos.isNotEmpty()) {
                    url = logos[0]
                }


                if (!productList.isNullOrEmpty()) {
                    var product = productList[0]
                    product?.let { offerList ->
                        var merWeb = offerList.spuOffer.merchantWeb
                        merWeb?.let {
                            shopName = merWeb.merchantName ?: ""
                            subOrNot = merWeb.subOrNot
                        }
                    }
                }
            } else {
                binding.leftImgTxtLay.gone()
            }
            if (url.isBlank() && shopName.isBlank()) {
                return
            }
            if (type == 2) {
//                && prdNum > 1
//            YYLogUtils.e("type == 2 && prdNum > 1")
                binding.holdLay.visible()
                binding.brandTxt.gone()
                binding.brandImgLay.gone()

                binding.holdTxt.text = prdNum.toString()
                binding.holdImg1Lay.gone()
                binding.holdImg2Lay.gone()
                binding.holdImg3Lay.gone()
                binding.holdImg4Lay.gone()
                binding.holdImg4.gone()
                binding.holdImg4Layer.gone()
                url.let {
                    product.offerList?.let { logos ->
                        binding.holdImgLay.visible()
                        if (logos.isNotEmpty()) {
                            binding.holdImg1Lay.visible()
                            binding.holdImg1.enableCorner(14.dp)
                            ImageUtils.loadImage(
                                context,
                                logos[0]?.spuOffer?.merchantWeb?.logo,
                                binding.holdImg1
                            )
                        }
                        if (logos.size > 1 && prdNum > 1) {
                            binding.holdImg2Lay.visible()
                            binding.holdImg2.enableCorner(14.dp)
                            ImageUtils.loadImage(
                                context,
                                logos[1]?.spuOffer?.merchantWeb?.logo,
                                binding.holdImg2
                            )
                        }

                        if (logos.size > 2 && prdNum > 2) {
                            binding.holdImg3Lay.visible()
                            binding.holdImg3.enableCorner(14.dp)
                            ImageUtils.loadImage(
                                context,
                                logos[2]?.spuOffer?.merchantWeb?.logo,
                                binding.holdImg3
                            )
                        }

                        if (logos.size > 3 && prdNum > 3) {
                            binding.holdImg4Lay.visible()
                            binding.holdImg4.visible()
                            binding.holdImg4.enableCorner(14.dp)
                            ImageUtils.loadImage(
                                context,
                                logos[3]?.spuOffer?.merchantWeb?.logo,
                                binding.holdImg4
                            )
                        }
                        if (logos.size > 3 && prdNum > 3) {
                            binding.holdImg4Layer.visible()
                        }
                    }
                }
            } else {

//            YYLogUtils.e(" binding.holdLay.gone()")
                binding.holdLay.gone()
                binding.holdImgLay.gone()
                //显示文字
                binding.brandTxt.visible()
                binding.brandTxt.text = shopName
                //处理图片
                binding.brandImgLay.visible()
                //是否显示已收藏
//                binding.brandImgColl.visibleOrGone(subOrNot)
                //不显示收藏
                binding.brandImgColl.gone()
                if (url.isBlank()) {
                    binding.brandImgFrg.gone()
                    binding.firstLetterLay.visible()
                    binding.firstLetterTxt.text = shopName.substring(0, 1).uppercase()
                } else {
                    binding.brandImgFrg.visible()
//                    YYLogUtils.e("  asdadad ------$url")
                    binding.brandImg.enableCorner(14.dp)
                    binding.brandImg.load(url)
                }
            }
        } else {
            //失效商品单独处理
            binding.holdLay.visible()
            binding.holdTxt.text = "0"
            binding.holdImgLay.gone()
            binding.brandTxt.gone()
            binding.brandImgLay.gone()
        }
    }

    private val theScope get() = (context as? AppCompatActivity?)?.lifecycleScope ?: MainScope()
    private fun showParityDialog(product: ProductF) {

        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                spmCnt = GTrackerAssistUtils.fetchElementValue(
                    spmPageValue,
                    SpmElementDef.ProductDetailPriceCheckClick
                ),
                params = spmMap(product)
            )
        )

        if (product.standardSpuIds.isNullOrEmpty()) {
            toastUI("data error")
            return
        }

        (context as? AppCompatActivity?)?.let { activity ->
            theScope.launch {
                SkGqlClient.skQuery(
                    FetchProductListByStdIdIgnoreCountryQuery(
                        stdProdcutIdQuery = StdProductIdQuery(
                            stdProductId = product.standardSpuIds!!,
                            saleableCountryFlag = false.optional(),
                            includeInValidProd = true.optional(),
                        ).optional()
                    ),
                    showDefaultLoading = true,
                )?.data?.fetchProductListByStdIdIgnoreCountry?.run {
                    this.mapNotNull { it?.productOffer }
                }?.let {
                    if (it.isNotEmpty()) {
                        PriceParityDialog.show(
                            activity.supportFragmentManager,
                            product = product,
                            it,
                            spmPageValue = SpmPageDef.PAGE_10210,
                        )
                    } else {
//                        toastUI("No more data")
                    }
                }

            }
        }
    }

}